package cn.cvs.web;

import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysSupplierService;
import cn.cvs.util.Constants;
import cn.cvs.util.DataTransfer;
import cn.cvs.util.PageSupport;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class SysSuppliersController {
    @Resource
    SysSupplierService sysSupplierService;

    //供应商列表
    @RequestMapping("/sys/supplier/list")
    public String list(@RequestParam(value = "querySupCode",required = false) String supCode,
                       @RequestParam(value = "querySupName",
                               required = false) String supName,@RequestParam(value = "pageIndex",required = false,
            defaultValue = "1")  Integer pageNo, Model model){
        model.addAttribute("querySupCode",supCode);
        model.addAttribute("querySupName",supName);
        //供应商列表
        List<Supplier> supplier = sysSupplierService.querySupplier(supCode, supName, pageNo, Constants.pageSize);
        model.addAttribute("supplierList",supplier);
        //totalCount 总记录数
        int count = sysSupplierService.queryCount(supCode, supName);
        model.addAttribute("totalCount",count);
        //currentPageNo 当前页码
        model.addAttribute("currentPageNo",pageNo);
        //totalPageCount 总页数
        PageSupport pageSupport = new PageSupport();
        //设置pageSize
        pageSupport.setPageSize(Constants.pageSize);
        //设置参与分页的总记录数
        pageSupport.setTotalCount(count);
        //获得总页数
        int totalPageCount = pageSupport.getTotalPageCount();
        model.addAttribute("totalPageCount",totalPageCount);
        return "supplier/list";
    }

    //跳转到添加供应商页面
    @RequestMapping("/sys/supplier/toAdd")
    public String toAdd(){
        return "supplier/add";
    }

    @PostMapping("/sys/supplier/add")
    public String add(Supplier supplier, HttpSession session, Model model){
        System.out.println("-----------------------------------------------------------------------------------");
        //验证用户是否登录
        SysUser login = (SysUser)session.getAttribute(Constants.USER_SESSION);
        System.out.println(supplier);
        if (login==null) {
            model.addAttribute("error","请登录后操作！");
            return "forward:toLogin";
        }

        //设置创建时间
        supplier.setCreatedTime(new Date());
        //设置创建者id
        supplier.setCreatedUserId(login.getId());
        int i = sysSupplierService.addSupplier(supplier);
        if (i>0) {
            //添加供应商成功
            //重定向回供应商列表
            return "redirect:/sys/supplier/list";
        }else{
            //添加用户失败
            throw new RuntimeException("添加供应商失败，请稍后再试！");
        }
    }

//    @PostMapping("/sys/supplier/add")
//    public String add(@Valid Supplier supplier, BindingResult bindingResult,
//                      HttpServletRequest request,
//                      HttpSession session, Model model,
//                      @RequestParam(value = "attachs",required = false) MultipartFile[] attachs){
//        //验证用户是否登录
//        SysUser login = (SysUser)session.getAttribute(Constants.USER_SESSION);
//        System.out.println(supplier);
//        if (login==null) {
//            model.addAttribute("error","请登录后操作！");
//            return "forward:toLogin";
//        }
//        if(bindingResult.hasErrors()){
//            //后台校验错误
//            throw new RuntimeException("后台数据校验错误");
//        }
//        for (int i = 0; i < attachs.length; i++) {
//            //保存图片
//            //idPic.transferTo(new File("xxx"));
//            //图片命名规则
//            //时间错_原名
//            //创建上传文件的新名字
//            String saveFileName = System.currentTimeMillis()
//                    +"_" +attachs[i].getOriginalFilename();
//            //服务器的保存位置
//            //  /工程目录/statics/uploadFiles/
//            //  工程目录 是指该工程在服务器上的具体位置
//            //  D:/web_server/tomcat9/webapps/ssmdemo-kf01/
//            //D:/web_server/tomcat9/webapps/ssmdemo-kf01/statics/uploadFiles/
//            String realPath = request.getSession()
//                    .getServletContext()
//                    .getRealPath("statics"+File.separator+"uploadFiles");
//            //创建保存的目录
//            File dir = new File(realPath);
//            if(!dir.exists()){
//                //不存在就创建
//                dir.mkdirs();
//            }
//            //创建要保存到服务器上的文件
//            File saveFile = new File(dir,saveFileName);
//            //保存文件
//            try {
//                attachs[i].transferTo(saveFile);
//            } catch (IOException e) {
//                e.printStackTrace();
//                throw new RuntimeException("保存图片失败",e);
//            }
//            //创建保存到数据库的图片路径信息
//            String path = File.separator+"statics"+File.separator
//                    +"uploadFiles"+File.separator+saveFileName;
//            if(i==0){
//                supplier.setEntPicPath(path);
//            }else{
//                supplier.setOrgPicPath(path);
//            }
//
//        }

//        //设置创建时间
//        supplier.setCreatedTime(new Date());
//        //设置创建者id
//        supplier.setCreatedUserId(login.getId());
//        int i = sysSupplierService.addSupplier(supplier);
//        if (i>0) {
//            //添加供应商成功
//            //重定向回供应商列表
//            return "redirect:/sys/supplier/list";
//        }else{
//            //添加用户失败
//            throw new RuntimeException("添加供应商失败，请稍后再试！");
//        }
//    }

    //跳转到修改页面
    @RequestMapping("/sys/supplier/toUpdate/{supId}")
    public String toUpdate(@PathVariable("supId") Integer id, Model model){
        Supplier supplier = sysSupplierService.queryById(id);
        model.addAttribute("supplier",supplier);
        return "/supplier/update";
    }

    //修改供应商
    @PostMapping("/supplier/update")
    public String updateSupplier(Supplier supplier,HttpSession session,Model model){
        //登陆验证
        SysUser login = (SysUser)session.getAttribute(Constants.USER_SESSION);
        if(login==null){
            //还没有登陆
            model.addAttribute("error", "请登录后操作！");
            return "forward:/toLogin";
        }
        //修改时间
        supplier.setUpdatedTime(new Date());
        //修改供应商id
        supplier.setUpdatedUserId(login.getId());
        int i = sysSupplierService.updateSupplier(supplier);
        if(i>0){
            //修改成功
            //重定向到供应商列表
            return "redirect:/sys/supplier/list";
        }else{
            throw new RuntimeException("修改失败，请稍后再试!");
        }
    }
    //异步删除
    @ResponseBody
    @DeleteMapping("/sys/supplier/del/{sid}")
    public Object delteSupplier(@PathVariable("sid") Integer id, HttpSession session, HttpServletRequest request){
        //返回值对象
        Map<String,Object> resultMap = new HashMap<>();
        SysUser loginUser =
                (SysUser)session.getAttribute(Constants.USER_SESSION);
        //判断是否登陆
        if(loginUser==null){
            resultMap.put("delResult", "noLogin");
            resultMap.put("msg", "请登陆后再操作");
            return JSON.toJSONString(resultMap);
        }
         //执行删除操作
        int i = sysSupplierService.delete(id);
        if (i>0){
            //删除成功
            resultMap.put("delResult","true");
        }else {
            //删除失败
            resultMap.put("delResult","false");
        }
        return JSON.toJSONString(resultMap);
    }
    //异步查看用户信息
    @ResponseBody
    @GetMapping("/sys/user/{sid}/view")
    public Object   asyViewUser(@PathVariable("sid") Integer id){
        //返回对象
        DataTransfer<Supplier> dto = new DataTransfer<>();
        try {
            Supplier supplier = sysSupplierService.queryById(id);
            if(supplier==null){
                dto.setStatus("nodata");
                return JSON.toJSONString(dto);
            }
            dto.setStatus("ok");
            dto.setData(supplier);
            return JSON.toJSONString(dto);
        } catch (Exception e) {
            e.printStackTrace();
            dto.setStatus("failed");
            return JSON.toJSONString(dto);
        }
    }

}
